package com.hnkywl.sts.service.cwgl;

import com.google.gson.Gson;
import com.hnkywl.sts.dao.BzjdrDao;
import com.hnkywl.sts.dao.cwgl.KmdmDao;
import com.hnkywl.sts.dao.organ.GsjgDao;
import com.hnkywl.sts.entity.cwgl.Kmdm;
import com.hnkywl.sts.entity.cwgl.VoucherItemData;
import com.hnkywl.sts.entity.sfgl.Sfk;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.BaseUtils;
import com.hnkywl.sts.util.MoneyUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-5-14
 * Time: 上午11:26
 * To change this template use File | Settings | File Templates.
 */
@Service
public class BzjdrService {
    private GsjgDao gsjgDao;
    private BzjdrDao bzjdrDao;
    private KmdmDao kmdmDao;

    public String findAllBzjdr(Integer sfklx, String zt, String bm, Date sfkrqStart, Date sfkrqEnd, String sbgs, Long sbgsId, String gldwMc, String cwsfpjlxMc, Integer cwsfZt, int pageNo, int pageSize) {
        Long nbgsIds = null;
        if (sbgsId != null && sbgs.equals(gsjgDao.get(sbgsId).getJc())) {
            nbgsIds = nbgsIds;
        }
        Page<Sfk> sfkPage = this.bzjdrDao.findAllBzjdr(sfklx, zt, bm, sfkrqStart, sfkrqEnd, sbgs, nbgsIds, gldwMc, cwsfpjlxMc, cwsfZt, pageNo, pageSize);
        List<Sfk> sfkList = sfkPage.getResult() == null ? new ArrayList<Sfk>() : sfkPage.getResult();
        if (sfkList.size() > 0) {
            sfkList = getCzztByPj(sfkList);
        }
        String sfkJson = BaseUtils.fetchCollectionToJson(sfkList, "id", "bm", "sfkrq", "pjhm", "sfklx", "khfksj", "gldw.qc", "sfje", "pjlx.z", "glkhh.qc", "kxlx", "czzt", "sbgs.jc", "shr.xm", "voucherNum", "nbkhh.qc", "kxsy.z");
        return "{\"total\":" + sfkPage.getTotalCount() + ",\"rows\":[" + sfkJson + "]}";
    }

    public List<Sfk> getCzztByPj(List<Sfk> sfkList) {
        for (Sfk p : sfkList) {
            String czzt = "";
            if (p.getInsertFlag() == 1 && p.getDeleteFlag() == 1) {
                czzt = "wdr";
            } else if (p.getInsertFlag() == 1 && p.getDeleteFlag() == 3) {
                czzt = "sccg";
            } else if (p.getInsertFlag() == 3 && p.getDeleteFlag() == 1) {
                czzt = "drcg";
            } else if (p.getInsertFlag() == 2 && p.getDeleteFlag() == 1 || p.getInsertFlag() == 2 && p.getDeleteFlag() == 3) {
                czzt = "drsb";
            } else if (p.getInsertFlag() == 3 && p.getDeleteFlag() == 2) {
                czzt = "scsb";
            } else {
                czzt = "null";
            }
            p.setCzzt(czzt);
        }
        return sfkList;
    }

    @Transactional
    public Map getVoucherMaster(Long id, Integer attachment, String uuid, String year, String mouth, Yg yg) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate = simple.format(new Date());
        Map<String, Object> voucherMaster = new HashMap<String, Object>();
        Sfk cwsf = this.bzjdrDao.get(id);
        voucherMaster.put("id", uuid);
        voucherMaster.put("vchrtypecode", "记");//凭证类别
        voucherMaster.put("acctyear", year != null ? year : "");//会计年度
        voucherMaster.put("acctperiod", mouth != null ? mouth : "");//会计期间
        voucherMaster.put("createdate", systemDate);//凭证日期
        voucherMaster.put("unitcode", cwsf.getCreateOrgan() != null && cwsf.getCreateOrgan().getJiuqiUnitCode() != null ? cwsf.getCreateOrgan().getJiuqiUnitCode() : "");//组织机构代码
        voucherMaster.put("acctbookcode", "01");//账薄标识
        voucherMaster.put("createuser", yg.getXm());//制单人
        voucherMaster.put("attachment", attachment);//附件张数
        voucherMaster.put("memo", "");//备注
        voucherMaster.put("companyId", this.findBzjdrDetail(id).getSbgs().getId());//公司ID
        return voucherMaster;
    }

    //财务收付分录
    @Transactional
    public String findBzjdrFl(Long id) {
        Sfk cwsf = this.bzjdrDao.get(id);
        List<Map> list = this.bzjdrDao.getVoucher(cwsf);
        List<Map> txcdJson = new ArrayList<Map>();
        Double credit = 0d;
        Double debit = 0d;
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> voucherItem = (Map<String, Object>) list.get(i);
            voucherItem.put("zy", voucherItem.get("digest"));
            voucherItem.put("km", voucherItem.get("subjectname"));
            voucherItem.put("jf", voucherItem.get("debit"));
            voucherItem.put("df", voucherItem.get("credit"));
            debit += Double.valueOf((voucherItem.get("natural_debit_currency") == null ? 0d : voucherItem.get("natural_debit_currency")).toString());
            credit += Double.valueOf((voucherItem.get("natural_credit_currency") == null ? 0d : voucherItem.get("natural_credit_currency")).toString());
            txcdJson.add(voucherItem);
        }
        String total = "合计：" + MoneyUtils.change(debit);
        return "{\"rows\":" + new Gson().toJson(txcdJson) + ",\"footer\":[{\"km\":\"" + total + "\",\"natural_debit_currency\":" + debit + ",\"natural_credit_currency\":" + credit + "}]}";
    }


    @Transactional
    public Map getU8VoucherItems(Long id, String uuid, List<VoucherItemData> voucherItemDataList, Date documentDate) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate = simple.format(new Date());
        Sfk cwsf = this.bzjdrDao.get(id);
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map> list = this.bzjdrDao.getVoucher(cwsf);
        DecimalFormat df = new DecimalFormat("#.##");
        //凭证分录信息
        List<Map> items = new ArrayList<Map>();
        int order = 1;
        for (Map m : list) {
            Map<String, Object> voucherItem = new HashMap<String, Object>();
            //voucherItem.put("id", order);//唯一标识
            //voucherItem.put("vchrid", uuid);//凭证主表ID
            voucherItem.put("entry_id", order);//分录编号
            voucherItem.put("account_code", m.get("account_code") != null ? m.get("account_code") : "");//科目代码
//                voucherItem.put("subjectname", item.getKmdm() != null && item.getKmmc() != null ? item.getKmmc() : "");//科目名称
            voucherItem.put("natural_debit_currency", m.get("natural_debit_currency") != null ? df.format(m.get("natural_debit_currency")) : "0.00");//借方金额
            voucherItem.put("natural_credit_currency", m.get("natural_credit_currency") != null ? df.format(m.get("natural_credit_currency")) : "0.00");//贷方金额
//                voucherItem.put("qty", item.getSl() != null ? item.getSl() : 0);//数量
            voucherItem.put("unit_price", "0");//单价,在科目有数量核算时，填写此项
            voucherItem.put("debit_quantity", "0");//借方数量,在科目有数量核算时，填写此项
            voucherItem.put("credit_quantity", "0");//贷方数量,在科目有数量核算时，填写此项
            voucherItem.put("currency", "CNY");//货币代码
            voucherItem.put("exchange_rate2", "1.000000");//汇率
//                voucherItem.put("orgnd", item.getJfje() != null ? df.format(item.getJfje()) : "0.00");//借方原币
//                voucherItem.put("orgnc", item.getDfje() != null ? df.format(item.getDfje()) : "0.00");//贷方原币
            voucherItem.put("settlement", "");//结算方式,在科目是银行或往来时，可以填写此项
            voucherItem.put("document_id", "");//票据号，在科目是银行或往来时，可以填写此项
            voucherItem.put("document_date", systemDate);//票据日期，在科目是银行或往来时，可以填写此项
            voucherItem.put("abstract", m.get("abstract") != null ? m.get("abstract") : "");//摘要
//                voucherItem.put("bizno", "");//业务号
            Map<String, String> fzhsMap = new HashMap<String, String>();
            Map<String, Map> xjllxmMap = new HashMap<String, Map>();
            fzhsMap = this.findFzhsByMap(cwsf, m, fzhsMap, xjllxmMap);
            voucherItem.put("auxiliary_accounting", fzhsMap);
            voucherItem.put("cash_flow", xjllxmMap);
            items.add(voucherItem);
            order++;
        }
        result.put("items", items);
        return result;
    }

    private Map<String, String> findFzhsByMap(Sfk sfk, Map<Object, String> map, Map<String, String> fzhsMap, Map<String, Map> xjllxmMap) {
        DecimalFormat df = new DecimalFormat("#.##");
        //1.更具公司还有代码查询科目代码
        Kmdm kmdm = kmdmDao.findKmdmDetailByGs(sfk.getSbgs().getId(), map.get("account_code"));
        if (kmdm == null) {
            kmdm = kmdmDao.findKmdmDetailByGs(YgService.getCurrentYgZgGsId(), map.get("account_code"));
        }
        //2.现金流量项目
        if (kmdm != null && kmdm.getXjllsx() != null && !"".equals(kmdm.getXjllsx()) && kmdm.getXjllsx().equals("Y")) {
            if (sfk.getSfklx() == 1 || sfk.getSfklx() == 2) {
                fzhsMap.put("item_id", "04");
            } else {
                fzhsMap.put("item_id", "01");
            }
            Map value = new HashMap<String, Double>();
            Double d = map.get("natural_debit_currency") != null ? Double.parseDouble(df.format(map.get("natural_debit_currency"))) : 0.00;
            Double c = map.get("natural_credit_currency") != null ? Double.parseDouble(df.format(map.get("natural_credit_currency"))) : 0.00;
            value.put("debit", d);
            value.put("credit", c);
            value.put("md", Math.abs(d - c));
            value.put("ccode", map.get("account_code"));
            if (sfk.getSfklx() == 1 || sfk.getSfklx() == 2) {
                xjllxmMap.put("04", value);
            } else {
                xjllxmMap.put("01", value);
            }
        }//3.其他项目
        else if (kmdm != null && kmdm.getTyfzhsmc() != null && kmdm.getTyfzhsys() != null) {
            fzhsMap.put("item_id", kmdm.getTyfzhsys().getCode());
        } else {
            if (map.get("dept_id") != null && !map.get("dept_id").toString().equals("")) {
                fzhsMap.put("dept_id", map.get("dept_id"));
            }
            if (map.get("personnel_id") != null && !map.get("personnel_id").toString().equals("")) {
                fzhsMap.put("personnel_id", map.get("personnel_id"));
            }
            if (map.get("cust_id") != null && !map.get("cust_id").toString().equals("")) {
                fzhsMap.put("cust_id", map.get("cust_id"));
            }
            if (map.get("supplier_id") != null && !map.get("supplier_id").toString().equals("")) {
                fzhsMap.put("supplier_id", map.get("supplier_id"));
                fzhsMap.put("operator", "-");
            }
        }
        return fzhsMap;
    }

    @Transactional
    public void bzjdrChangeDrrq(Long cwsfId, Date date) {
        Sfk cwsf = this.bzjdrDao.get(cwsfId);
        cwsf.setDrrq(date);
        bzjdrDao.save(cwsf);
    }

    @Transactional
    public Map getRevokeInfo(Long id) {
        Map<String, Object> revokeInfo = new HashMap<String, Object>();
        Sfk result = bzjdrDao.get(id);
        if (result == null) {
            throw new RuntimeException("未获取凭证信息!");
        }
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("MM");
        revokeInfo.put("id", result.getUuid());//凭证ID
        revokeInfo.put("vchrid", result.getVoucherId());//凭证ID
        revokeInfo.put("unitcode", result.getCreateOrgan() != null && result.getCreateOrgan().getJiuqiUnitCode() != null ? result.getCreateOrgan().getJiuqiUnitCode() : "");//单位代码
        revokeInfo.put("vchrtypecode", "记");//会计年度
        revokeInfo.put("acctyear", result.getAcctyear());//会计年度
        revokeInfo.put("acctperiod", simpleDateFormat3.format(result.getDrrq()));//会计年度
        revokeInfo.put("vchrnum", result.getVoucherNum());//凭证号

        return revokeInfo;
    }


    @Transactional
    public Sfk findBzjdrDetail(Long id) {
        return this.bzjdrDao.get(id);
    }

    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }

    @Autowired
    public void setBzjdrDao(BzjdrDao bzjdrDao) {
        this.bzjdrDao = bzjdrDao;
    }

    @Autowired
    public void setKmdmDao(KmdmDao kmdmDao) {
        this.kmdmDao = kmdmDao;
    }
}
